package com.wolan.utils.interceptor;

import com.wolan.exception.BusinessException;
import com.wolan.exception.BusinessExceptionFactory;
import com.wolan.model.res.ResponseEntity;
import com.wolan.model.res.StatusInfo;
import com.wolan.exception.WolinkException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    protected Logger logger = Logger.getLogger(getClass());
    @Autowired
    private BusinessExceptionFactory exceptionFactory;

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<Void> handle(Exception ex) {
        logger.error("", ex);
        ResponseEntity<Void> result = new ResponseEntity<>();
        if(ex instanceof BusinessException) {
            String errorCode = ((BusinessException) ex).getErrorCode();
            result.setErrorCode(errorCode);
            result.setMessage(((BusinessException) ex).getMessage());
        } else if(ex instanceof WolinkException) {
            String errorCode = ((WolinkException) ex).getErrorCode() + "";
            BusinessException be = exceptionFactory.createBusinessException(errorCode);
            result.setErrorCode(errorCode);
            result.setMessage(be.getMessage());
        } else {
            result.setErrorCode(StatusInfo.REQUEST_FAILURE);
            result.setMessage(StatusInfo.REQUEST_FAILURE_MSG);
        }
        return result;
    }
}
